package com.zucc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.zucc.controller.req.ResourceAddReq;
import com.zucc.controller.req.ResourceModifyReq;
import com.zucc.controller.req.ResourceSearchReq;
import com.zucc.controller.resp.NewsResp;
import com.zucc.controller.resp.ResourceResp;
import com.zucc.entity.*;
import com.zucc.entity.base.MyMapper;
import com.zucc.exception.SyzxException;
import com.zucc.service.ResourceService;
import com.zucc.service.base.MyServiceImpl;
import com.zucc.service.base.PageData;
import com.zucc.util.MyPageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : charspan
 * @Description :
 * @create : 2021-12-11 8:56 下午
 */
@Service
public class ResourceServiceImpl extends MyServiceImpl<Resource> implements ResourceService {

    @javax.annotation.Resource
    private AttachmentMapper attachmentMapper;
    
    @javax.annotation.Resource
    private CategoryMapper categoryMapper;

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    @Override
    public MyMapper<Resource> mapper() {
        return resourceMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ResourceAddReq req) {
        // 判断附件存在
        Attachment attachment = attachmentMapper.selectByPrimaryKey(req.getAttachmentId());
        if (Objects.isNull(attachment) || attachment.getDelFlag().intValue() == 1) {
            throw new SyzxException("系统找不到相应编号的附件信息");
        }
        // 判断附件没有被使用
        Example exp = new Example(com.zucc.entity.Resource.class);
        exp.createCriteria().andEqualTo("delFlag", 0)
                .andEqualTo("attachmentId", req.getAttachmentId());
        Resource resourceExist = resourceMapper.selectOneByExample(exp);
        if (Objects.nonNull(resourceExist)) {
            throw new SyzxException("当前附件已被其他资源绑定");
        }
        Resource resource = new Resource();
        BeanUtil.copyProperties(req, resource);
        resource.setDownloadTimes(0);
        resource.setDelFlag(0);
        resource.setCreateTime(DateUtil.date());
        resource.setModifyTime(DateUtil.date());
        resource.setApprovalStatus(0);
        super.saveKey(resource);
        attachment.setBuzId(resource.getId());
        attachmentMapper.updateByPrimaryKeySelective(attachment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(ResourceModifyReq req) {
        Resource resourceExist = super.findById(req.getId());
        if (Objects.isNull(resourceExist) || resourceExist.getDelFlag().intValue() == 1) {
            throw new SyzxException("系统找不到相应编号的资源信息");
        }
        BeanUtil.copyProperties(req, resourceExist, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        resourceExist.setModifyTime(DateUtil.date());
        super.updateSelective(resourceExist);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOne(Long id) {
        Resource resourceExist = super.findById(id);
        if (Objects.isNull(resourceExist) || resourceExist.getDelFlag().intValue() == 1) {
            throw new SyzxException("系统找不到相应编号的资源信息");
        }
        resourceExist.setDelFlag(1);
        resourceExist.setDeleteTime(DateUtil.date());
        super.updateSelective(resourceExist);
    }

    @Override
    public PageData<ResourceResp> page(ResourceSearchReq req) {
        Example example = new Example(Resource.class);
        example.setOrderByClause("modify_time DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delFlag", 0);

        if (StrUtil.isNotBlank(req.getName())) {
            criteria.andLike("name", "%" + req.getName() + "%");
        }
        if (Objects.nonNull(req.getCategoryId())) {
            criteria.andEqualTo("categoryId", req.getCategoryId());
        }
        if (StrUtil.isNotBlank(req.getRemarks())) {
            criteria.andLike("remarks", "%" + req.getRemarks() + "%");
        }
        if (Objects.nonNull(req.getApprovalStatus())) {
            criteria.andEqualTo("approvalStatus", req.getApprovalStatus());
        }

        PageData<Resource> pageData = super.findByPage(req, example);
        PageData<ResourceResp> convert = MyPageUtil.convert(pageData, ResourceResp.class);
        List<Long> categoryIds = convert.getList().stream().map(ResourceResp::getCategoryId).distinct().collect(Collectors.toList());
        List<Category> list = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            list.add(categoryMapper.selectByPrimaryKey(categoryId));
        }
        Map<Long, String> categoryMap = list.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        for (ResourceResp resourceResp : convert.getList()) {
            resourceResp.setCategoryName(categoryMap.get(resourceResp.getCategoryId()));
        }
        return convert;
    }
}
